package vip.george.sentinel1.config;

import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.CommonsClientAutoConfiguration;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author george
 * @since 2023/7/6
 * <p>nacos配置</p>
 */
@Configuration
@ConditionalOnNacosDiscoveryEnabled
@AutoConfigureBefore({SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class})
public class NacosConfig {

    @Value("${spring.profiles.active}")
    public String profile;

    public NacosConfig() {
    }

//    @Bean
//    @ConditionalOnMissingBean
//    public NacosDiscoveryProperties nacosProperties() {
//        return new NacosDiscoveryProperties();
//    }
//
//    @Bean
//    @ConditionalOnMissingBean
//    public DiscoveryClient nacosDiscoveryClient(NacosServiceDiscovery discoveryProperties) {
//        return new NacosDiscoveryClient(discoveryProperties);
//    }


    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = {"spring.cloud.nacos.discovery.watch.enabled"}, matchIfMissing = true)
    public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties) {
        //原来的元数据全部清空
        nacosDiscoveryProperties.setMetadata(new HashMap<>());
        //更改服务详情中的元数据，增加服务注册时间等信息
        nacosDiscoveryProperties.getMetadata().put("startup.time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        nacosDiscoveryProperties.getMetadata().put("spring.profiles.active",profile);
        nacosDiscoveryProperties.getMetadata().put("version","v1.0");
        return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties);
    }
}
